<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加分类 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addCategary">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        class="tablemargin"
        :data="categariesList"
        border
        stripe
        show-index
        empty-text="没有数据"
        index-text="#"
        :columns="columns"
        :expand-type="false"
        :selection-type="false"
        :show-row-hover="false"
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen; font-size: 18px;"
          ></i>
          <i class="el-icon-error" v-else style="color: ren; font-size: 18px;"></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑商品" placement="top" :enterable="false">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="getEditCategories(scope.row)"
              size="mini"
            >编辑</el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除商品" placement="top" :enterable="false">
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removeCategoriesById(scope.row.cat_id)"
              size="mini"
            >删除</el-button>
          </el-tooltip>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="query.pagenum"
        :page-sizes="[5,10,15,20]"
        :page-size="query.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加分类对话框 -->
      <el-dialog title="添加分类" :visible.sync="addCategaryDialogVisible" @close="clearAddForm">
        <el-form
          :model="addCateForm"
          :rules="addCategaryFormRules"
          ref="addCategaryFormRef"
          label-width="100px"
        >
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类">
            <el-cascader
              v-model="selectedKeys"
              :options="parentData"
              :props="cascaderProps"
              @change="handleChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategaryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="tianjiafenlei">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑商品分类 -->
      <el-dialog title="编辑商品" :visible.sync="editCategaryDialogVisible" @close="clearEditForm">
        <el-form
          :model="editCateForm"
          :rules="addCategaryFormRules"
          ref="editCategaryFormRef"
          label-width="100px"
        >
          <el-form-item label="商品名称">{{shangpinmingcheng}}</el-form-item>

          <el-form-item label="新的名称" prop="cat_name">
            <el-input v-model="editCateForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCategaryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editSubmit">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addCategaryDialogVisible: false,
      editCategaryDialogVisible: false,
      categariesList: [],
      parentData: [],
      selectedKeys: [],
      total: 0,
      editId: 0,
      shangpinmingcheng: '',
      query: {
        type: 3,
        pagenum: 1,
        pagesize: 10,
      },
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'isok',
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level',
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
        },
      ],
      addCateForm: {
        // 将要添加的分类名
        cat_name: '',
        // 父级分类的Id
        cat_pid: 0,
        // 分类的等级，默认要添加的是1级分类
        cat_level: 0,
      },
      addCategaryFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: 'true',
      },
      editCateForm: {
        cat_name: '',
      },
    }
  },
  created() {
    this.getCategariesList()
  },
  methods: {
    async getCategariesList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.query,
      })
      console.log(res)
      if (res.meta.status !== 200) return
      this.categariesList = res.data.result
      this.total = res.data.total
    },
    // 编辑商品
    getEditCategories(cate) {
      // console.log('shangpin:', cate)
      this.shangpinmingcheng = cate.cat_name
      this.editId = cate.cat_id
      this.editCategaryDialogVisible = true
    },
    // 编辑提交
    async editSubmit() {
      // console.log(this.editCateForm.cat_name);
      // console.log(this.editId);
      const { data: res } = await this.$http.put(
        `categories/${this.editId}`,
        this.editCateForm
      )
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error('修改失败')
      this.getCategariesList()
      this.$message.success('修改成功')
      this.editCategaryDialogVisible = false
    },
    // 编辑商品重置
    clearEditForm() {
      ;(this.editCateForm.cat_name = ''),
        (this.editId = 0),
        (this.shangpinmingcheng = '')
    },
    // 删除商品
    async removeCategoriesById(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm')
        return this.$message.info('已取消删除操作')
      const { data: res } = await this.$http.delete(`categories/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.getCategariesList()
      this.$message.success('删除成功')
    },
    // 分页区域
    // 每页条数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.query.pagesize = val
      this.getCategariesList()
    },
    // 当前页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.query.pagenum = val
      this.getCategariesList()
    },
    // 添加分类
    addCategary() {
      this.addCategaryDialogVisible = true
      this.toGetParentData()
    },
    // 获取父级分类数据
    async toGetParentData() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      console.log('res:', res)
      if (res.meta.status !== 200) return
      this.parentData = res.data
    },
    // 提交添加分类
    async tianjiafenlei() {
      this.$refs.addCategaryFormRef.validate(async (valid) => {
        if (!valid) return
      })
      const { data: res } = await this.$http.post(
        'categories',
        this.addCateForm
      )
      if (res.meta.status !== 201) return this.$message.error('添加失败')
      this.getCategariesList()
      this.$message.success('添加成功')
      this.addCategaryDialogVisible = false
    },
    // 关闭对话框清除添加分类表单
    clearAddForm() {
      this.$refs.addCategaryFormRef.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    handleChange() {
      if (this.selectedKeys.length > 0) {
        // 父级分类的Id
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // 为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length
        return
      } else {
        // 父级分类的Id
        this.addCateForm.cat_pid = 0
        // 为当前分类的等级赋值
        this.addCateForm.cat_level = 0
      }
    },
  },
}
</script>
<style lang="less" scoped>
.tablemargin {
  margin: 15px 0;
}
.el-cascader {
  width: 100%;
}
</style>
